<?php
namespace WXAPI\Controller;
use Think\Controller;
use OSS\OssClient;
use OSS\Core\OssException;
ini_set('max_execution_time', '0');
ini_set('memory_limit', '888M');
class OrderController extends BaseController{
    /**
     * 析构流函数
     */
    public function  __construct() {
        parent::__construct();
    }
    
    public function index(){
        echo I('callback')."(".json_encode([
            'code'=>'200',
            'infos'=>'连接成功！'
        ]).")";
    }
    /**
     * 同步订单到贝菲锁具
     * POST
     * https://api.dinviet.cn/api/third/tlc?token=31d94fcb27ab899771b1e2808447e6cf&type=order
     */
    public function send_orders($order_id = 0){
        //如果有缓存，证明已经传过数据，那么需要去最新的数据7430913
        //echo tpCache("send_orders");die();
        $where = "store_id = 4031";
        if($order_id == 0){
            if(tpCache("send_orders") != null){
                $where.=' and order_id > '.tpCache("send_orders");
            }else{
                $sync_order_id = M('sync_order')->where(['id'=>1])->getField('sync_order_id');
                if($sync_order_id != null){
                     $where.=' and order_id > '.$sync_order_id;
                }
            }
        }else{
            $where.=' and order_id = '.$order_id;
        }    
        
        $data_count =  M('order')->where($where)->count();
        //判断是否有最新的数据，没有就返回
        if($data_count <= 0){
            return;
        }
        // tpCache("send_orders",7430913);

        $Page = intval($data_count / 100);
        if($data_count % 100 > 0){
            $Page = $Page + 1;
        }
        
        for ($i=0; $i<$Page; $i++){
            $cPage = $i;
            $cPage = $cPage * 100;
            $data =  M('order')->where($where)->limit($cPage, 100)->select();
            if($data){
                $count = 0;
                foreach ($data as $key=>$value){
                    $order_goods =  M('order_goods')->field('rec_id,order_id,goods_id,goods_name,goods_num,market_price,goods_price,cost_price,member_goods_price,give_integral,spec_key,spec_key_name,prom_msg,is_comment,prom_type,prom_id,is_send,delivery_id,sku,store_id,commission,is_checkout,deleted,distribut,distribut_price,is_order_refund,jifen_price,points,floating')->where('order_id='.$value['order_id'])->select();
                    if($order_goods){
                        foreach ($order_goods as $keys=>$values){
                            $order_goods[$keys]['goods_name'] = addslashes($values['goods_name']);//addslashes 转义
                        }
                        $data[$key]['product data'] = $order_goods;
                    }else{
                        $data[$key]['product data'] = [];
                    }
                    //判断是否最后一个数据
                    if($i == $Page - 1){
                        $count++;
                        if ($count == count($data)  && $order_id == 0) {
                            tpCache("send_orders",$value['order_id'],2592000000);
                            M('sync_order')-> where('id=1')->setField('sync_order_id',$value['order_id']);
                        }
                    }
                    unset($order_goods);
                }
                
                $json_data=array("token"=>"9172a524249c4e0641cc12b69ac3c1bf","data"=>json_encode($data,true),"type"=>'order');//post参数
                $header = array('Authorization: put_order');
                $put_order = $this->https_post('https://api.dinviet.cn/api/third/tlc',$json_data);
            }
        }
        
        $put_data = -1;
        if ($order_id > 0) {
            $put_data = json_decode($put_order,true)['code'];
        }
        
        $json_str = json_encode(['status'=>0,'put_data'=>$put_data,'where'=>$where,'data_count'=>$data_count,'data'=>[],'msg'=>'订单同步数据完成'],true);
        exit($json_str);
        
    }


    /**
     * 同步订单到大立商贸
     * POST
     * https://api.hr.jialans.cn/api/third/tlc?token=31d94fcb27ab899771b1e2808447e6cf&type=order
     */
    public function send_4268_orders($order_id = 0){
        //如果有缓存，证明已经传过数据，那么需要去最新的数据7430913
        //echo tpCache("send_orders_4268");die();
        $where = "store_id = 4268";
        if($order_id == 0){
            if(tpCache("send_orders_4268") != null){
                $where.=' and order_id > '.tpCache("send_orders_4268");
            }else{
                $sync_order_id = M('sync_order')->where(['id'=>2])->getField('sync_order_id');
                if($sync_order_id != null && $sync_order_id != 0){
                     $where.=' and order_id > '.$sync_order_id;
                }
            }
        }else{
            $where.=' and order_id = '.$order_id;
        }

        $data_count =  M('order')->where($where)->count();
        //判断是否有最新的数据，没有就返回
        if($data_count <= 0){
            return;
        }
        // tpCache("send_orders_4268",7430913);

        $Page = intval($data_count / 100);
        if($data_count % 100 > 0){
            $Page = $Page + 1;
        }
        
        for ($i=0; $i<$Page; $i++){
            $cPage = $i;
            $cPage = $cPage * 100;
            $data =  M('order')->where($where)->limit($cPage, 100)->select();
            if($data){
                $count = 0;
                foreach ($data as $key=>$value){
                    $order_goods =  M('order_goods')->field('rec_id,order_id,goods_id,goods_name,goods_num,market_price,goods_price,cost_price,member_goods_price,give_integral,spec_key,spec_key_name,prom_msg,is_comment,prom_type,prom_id,is_send,delivery_id,sku,store_id,commission,is_checkout,deleted,distribut,distribut_price,is_order_refund,jifen_price,points,floating')->where('order_id='.$value['order_id'])->select();
                    if($order_goods){
                        foreach ($order_goods as $keys=>$values){
                            $order_goods[$keys]['goods_name'] = addslashes($values['goods_name']);//addslashes 转义
                        }
                        $data[$key]['product data'] = $order_goods;
                    }else{
                        $data[$key]['product data'] = [];
                    }
                    //判断是否最后一个数据
                    if($i == $Page - 1){
                        $count++;
                        if ($count == count($data) && $order_id == 0) {
                            tpCache("send_orders_4268",$value['order_id'],2592000000);
                            M('sync_order')-> where('id=2')->setField('sync_order_id',$value['order_id']);
                        }
                    }
                    unset($order_goods);
                }
                
                $json_data=array("token"=>"9172a524249c4e0641cc12b69ac3c1bf","data"=>json_encode($data,true),"type"=>'order');//post参数
                $header = array('Authorization: put_order');
                $put_order = $this->https_post('https://api.hr.jialans.cn/api/third/tlc',$json_data);
            }
        }
        $put_data = -1;
        if ($order_id > 0) {
            $put_data = json_decode($put_order,true)['code'];
        }
        
        $json_str = json_encode(['status'=>0,'put_data'=>$put_data,'where'=>$where,'data_count'=>$data_count,'data'=>[],'msg'=>'订单同步数据完成'],true);
        exit($json_str);
        
    }

    public function https_post($url,$data){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        
        $result = curl_exec($curl);
        if(curl_errno($curl)) {
            return 'Errno'.curl_errno($curl);
        }
        curl_close($curl);
        return $result;
    }


    /**
     * 维修
     */
    public function shenqing_weixiu(){

        //接受post参数
        $object = file_get_contents('php://input');
        $_POST = (json_decode($object, true));
        $order_id = (int)$_POST['order_id'];
        $goods_keys = $_POST['goods_keys'];
        $goods_nums = $_POST['goods_nums'];
        $goods_prices = $_POST['goods_prices'];
        $goods_pointss = $_POST['goods_pointss'];
        $tuihuo_time = $_POST['tuihuo_time'];
        $type = (int)$_POST['type'];
        $remark =  $_POST['remark'];
//        dump('维修'.$order_id.'*'.$goods_id.'*'.$type.'*'.$remark);exit;
        if($order_id == 0){
            exit(json_encode(['status'=>-1,'msg'=>'请传入订单id']));
        }
        $order = M('order o')
            ->where(['o.order_id'=>$order_id])
            ->find();

        $tuihuo_status = M('store')->where(['store_id'=>$order['store_id']])->getField('tuihuo_status');

        if($tuihuo_status != 1){
            $this->error('店铺已经长关店');
        }

        if($order){
            foreach ($goods_keys as $key=>$value){
                $spec_key = $value;
                $order_goods=M('order_goods')->where('order_id='.$order_id.' and spec_key="'.$spec_key.'"')->find();
                M('fix_goods_store')->add([
                    'order_sn'=>$order['order_sn'],
                    'order_id'=>$order_id,
                    'goods_id'=>$order_goods['goods_id'],
                    'user_id'=>$order['user_id'],
                    'store_id'=>$order['store_id'],
                    'type'=>$type,
                    'goods_num'=>$goods_nums[$key],
                    'remark'=>$remark,
                    'fix_time'=>time(),
                    'addtime'=>strtotime(date("Y-m-d H:i:s", time())),
                    'member_goods_price'=>$order_goods['member_goods_price'],
                    'spec_key'=>$spec_key,
                    'is_create'=>0,
                ]);
            }
            exit(json_encode(['status'=>0,'msg'=>'申请成功！']));
        }
    }

    /**
     * 退货
     */
    public function shenqing_tuihuo(){

        //接受post参数
        $object = file_get_contents('php://input');
        $_POST = (json_decode($object, true));
        $order_id = (int)$_POST['order_id'];
        $goods_keys = $_POST['goods_keys'];
        $goods_nums = $_POST['goods_nums'];
        $goods_prices = $_POST['goods_prices'];
        $goods_pointss = $_POST['goods_pointss'];
        $tuihuo_time = $_POST['tuihuo_time'];
        $refund_type = (int)$_POST['type'];
        $remark =  $_POST['remark'];
//        dump(I('post.'));exit;
        if($order_id == 0){
            exit(json_encode(['status'=>-1,'msg'=>'请传入订单id']));
        }

        $order = M('order o')
            ->where(['o.order_id'=>$order_id])
            ->find();

        if (empty($order['driver_time'])){
            exit(json_encode(['status'=>-1,'msg'=>'该订单未收货，无法申请退货']));
        }
        if($order['driver_id'] === 0){
            exit(json_encode(['status'=>-1,'msg'=>'该订单未分配司机']));
        }
        $order_sn = get_order_sn();

        foreach ($goods_keys as $key=>$value){
            $spec_key = $value;
            $order_goods=M('order_goods')->where('order_id='.$order_id.' and spec_key="'.$spec_key.'"')->find();

            $return_open = M('goods g')->field('s.open_return,g.goods_name')->join('ty_store s on s.store_id = g.store_id','LEFT')->where(['g.goods_id'=>$order_goods['goods_id']])->find();
//            dump($return_open['goods_name']);exit;
            if($return_open['open_return'] == 0){
                exit(json_encode(['status'=>-1,'msg'=>'商品：'.$return_open['goods_name'].'店铺关闭了售后']));
            }
            $return_num = M('return_goods_store')->where(['order_id'=>I('order_id'),'status'=>['neq',3],'goods_id'=>$order_goods['goods_id'],'spec_key'=>$spec_key])->sum('goods_num');
            if($return_num >= $order_goods['goods_num']){
                exit(json_encode(['status'=>-1,'msg'=>'商品：'.$return_open['goods_name'].'已申请过退货']));
            }
            if($goods_nums[$key]>$order_goods['goods_num']-$return_num){
                exit(json_encode(['status'=>-1,'msg'=>'商品：'.$return_open['goods_name'].'退货数量超出订单数']));
            }
            M('return_goods_store')->add([
                'order_sn'=>$order['order_sn'],
                'return_order_sn'=>$order_sn,
                'order_id'=>$order_id,
                'fenbu_id'=>$order['fenbu_id'],
                'goods_id'=>$order_goods['goods_id'],
                'user_id'=>$order['user_id'],
                'store_id'=>$order['store_id'],
                'driver_id'=>$order['driver_id'],
                'goods_num'=>$goods_nums[$key],
                'remark'=>$remark,
                'tuihuo_time'=>time(),
                'addtime'=>time(),
                'member_goods_price'=>$order_goods['member_goods_price'],
                'points'=>$order_goods['points'],
                'reason'=>'',
                'spec_key'=>$spec_key,
                'yijia'=>$order['yijia'],
                'getorder'=>0,
                'ruku_time'=>'',
                'store_status'=>0,
                'refund_type'=>$refund_type,
                ]);
//            dump($d);exit;
        }
        exit(json_encode(['status'=>0,'msg'=>'申请成功！']));
    }

    /**
     * 退货备注
     */
    public function tuihuo_remark(){
        $list = ['放错区域','延迟发货','下多/下错', '配错/货不对版', '少货', '不合适', '质量问题', '破损', '比其他商城价格偏贵'];
        exit(json_encode(['status'=>0,'msg'=>'success','data'=>$list]));
    }

    
}
